package com.ygqh.baby.controller.admin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.model.MediaUploadResult;
import com.foxinmy.weixin4j.mp.api.MediaApi;
import com.foxinmy.weixin4j.mp.model.Menu;
import com.foxinmy.weixin4j.token.TokenHolder;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.constant.Constant;
import com.ygqh.baby.constant.RedisConstant;
import com.ygqh.baby.po.YgFileTemplate;
import com.ygqh.baby.po.YgPlatform;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.WxMpAuthorityService;
import com.ygqh.baby.service.YgFileTemplateService;
import com.ygqh.baby.service.YgPlatformService;
import com.ygqh.baby.utils.JsonUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Controller
@RequestMapping("/admin/template")
public class TemplateController extends BaseController<Object, java.lang.Long> {
	@Autowired
	private YgFileTemplateService ygFileTemplateService;
	@Autowired
	private WxMpAuthorityService wxMpAuthorityService;
	@Autowired
	private RedisDao redisDao;
	@Autowired
	private YgPlatformService ygPlatformService;

	@Value("${promotion.link}")
	protected String promotionLink;
	@Value("${small.appId}")
	private String smallAppId;

	@RequestMapping("searchImageList")
	@ResponseBody
	public List<YgFileTemplate> searchImageList(String q, QueryInfo queryInfo, FileType type) {

		List<YgFileTemplate> resultSet = ygFileTemplateService.find(type);

		Map<String, Object> map = new HashMap<String, Object>();
		for (YgFileTemplate t : resultSet) {
			String areaName = t.getAreaName();
			List<YgFileTemplate> areaList = new ArrayList<YgFileTemplate>();

			for (YgFileTemplate tt : resultSet) {
				if (tt.getAreaName().equals(areaName)) {
					areaList.add(tt);
				}
			}
			map.put(areaName, areaList);

		}
		return resultSet;
	}

	@RequestMapping("saveImg")
	@ResponseBody
	public Message saveImg(String img,String imgType) {
		YgFileTemplate ygimg = JsonUtils.toObject(img, YgFileTemplate.class);
		ygimg.setUpdateBy(getSession().getTrueName());
		ygimg.setUpdateTime(new Date());
		
		ygimg.setAreaName("");
		ygimg.setName("");
		ygimg.setLinkUrl("");
		String redisKey=String.format(RedisConstant.MALL_TEMPLATE_KEY, ygimg.getImgType().name());
		
		redisDao.del(redisKey);
		
		return ygFileTemplateService.saveOrUpdate(ygimg) == 1 ? SUCCESS_MESSAGE : ERROR_MESSAGE;

	}

	@RequestMapping("saveNewMall")
	@ResponseBody
	public Message saveNewMall(String img) {
		redisDao.set("newMall", img, 0);
		YgFileTemplate ygFileTemplate = ygFileTemplateService.find(FileType.Mall).get(0);
		ygFileTemplate.setImgPath(img);
		ygFileTemplateService.update(ygFileTemplate);
		return SUCCESS_MESSAGE;

	}

	@RequestMapping("getNewMall")
	@ResponseBody
	public YgFileTemplate getNewMall() {

		return ygFileTemplateService.find(FileType.Mall).get(0);

	}

	@RequestMapping("publishCustomMenu")
	@ResponseBody
	public Message publishCustomMenu(String menus, String platformNo) throws WeixinException {
		wxMpAuthorityService.publishCustomMenu(menus, platformNo);
		return SUCCESS_MESSAGE;
	}

	/**
	 * 获取公众号所有菜单
	 *
	 * @param platformNo
	 * @throws WeixinException
	 */
	@RequestMapping("getAllMenu")
	@ResponseBody
	public Message getAllMenu(String platformNo) throws WeixinException {
		String smallAppId = this.smallAppId;
		if (StringUtils.isNotBlank(platformNo) && !Constant.YIIGOO_PLATFORM_NO.equals(platformNo)) {
			YgPlatform platform = ygPlatformService.findByPlatformNo(platformNo, AppType.Small);
			smallAppId = platform.getAppId();
		}
		Map<String, Object> data = new HashMap<>();
		data.put("smallAppId", smallAppId);
		List<Menu> menuList = null;
		try {
			menuList = wxMpAuthorityService.getAllMenu(platformNo);
		} catch (WeixinException e) {
			e.printStackTrace();
		}
		data.put("menuList", menuList);
		return Message.success(data);
	}

	/**
	 * @param uploadFile
	 * @throws WeixinException
	 * @throws IOException
	 */
	@RequestMapping("uploadMedia")
	@ResponseBody
	public Map<Object, Object> uploadFile(@RequestParam("uploadFile") MultipartFile uploadFile, FileType fileType, ImgMedia imgType,
										  HttpServletRequest request, HttpServletResponse response) throws WeixinException, IOException {
		TokenHolder holder = wxMpAuthorityService.findTokenHolder();
		MediaApi mediaApi = new MediaApi(holder);
		InputStream is = uploadFile.getInputStream();
		MediaUploadResult result = mediaApi.uploadMedia(true, is, imgType.getTitle() + ".jpg");
		redisDao.set(imgType.name() + "MediaId", result.getMediaId(), 0);
		Map<Object, Object> map = new HashMap<Object, Object>();
		map.put("result", result);
		return map;
	}

	@RequestMapping("updateImageStatus")
	@ResponseBody
	public Message updateImageStatus(String name) {
		ygFileTemplateService.updateImageStatus(name);

		return SUCCESS_MESSAGE;
	}

	@RequestMapping("updateImageSort")
	@ResponseBody
	public Message updateImageSort(String list) {
		List<YgFileTemplate> listFile = JSON.parseObject(list, new TypeReference<List<YgFileTemplate>>() {
		});
		ygFileTemplateService.updateImageStatusByAreaName(listFile.get(0).getAreaName(), getSession().getTrueName(), new Date());
		ygFileTemplateService.insertFileByList(listFile, getSession().getTrueName(), new Date());
		return SUCCESS_MESSAGE;
	}

	@RequestMapping("saveCategory")
	@ResponseBody
	public Message saveCategory(@RequestParam String img,@RequestParam FileType fileType) {
		YgFileTemplate ygFileTemplate = new YgFileTemplate();
		List<YgFileTemplate> templateList = ygFileTemplateService.find(fileType);
		if (!CollectionUtils.isEmpty(templateList)) {
			ygFileTemplate.setId(templateList.get(0).getId());
		} else {
			ygFileTemplate.setAreaName(fileType.getName());
			ygFileTemplate.setName(fileType.getName());
			ygFileTemplate.setLinkUrl(promotionLink);
			ygFileTemplate.setImgType(fileType);
		}
		ygFileTemplate.setImgPath(img);
		ygFileTemplate.setUpdateBy(getSession().getTrueName());
		ygFileTemplate.setUpdateTime(new Date());
		if (ygFileTemplateService.saveOrUpdate(ygFileTemplate) == 1) {
			redisDao.set(String.format(RedisConstant.PAGE_TEMPLATE_PREFIX, fileType.name()), img, 0);
			return SUCCESS_MESSAGE;
		}
		return ERROR_MESSAGE;
	}

	@RequestMapping("findCategoryImg")
	@ResponseBody
	public Message findCategoryImg(FileType fileType) {
		return Message.success(ygFileTemplateService.findCategoryImg(fileType));
	}

	@RequestMapping("saveYiJiadianwMall")
	@ResponseBody
	public Message saveYiJiadianwMall(String img) {
		YgFileTemplate ygFileTemplate = new YgFileTemplate();
		ygFileTemplate.setName("壹家店");
		ygFileTemplate.setLinkUrl(promotionLink);
		ygFileTemplate.setImgPath(img);
		ygFileTemplate.setAreaName("mall");
		ygFileTemplate.setImgType(FileType.YiJiaDian);
		ygFileTemplate.setUpdateBy(getSession().getTrueName());
		ygFileTemplate.setUpdateTime(new Date());
		List<YgFileTemplate> t = ygFileTemplateService.find(FileType.YiJiaDian);
		if (t != null && t.size() == 1)
			ygFileTemplate.setId(t.get(0).getId());

		ygFileTemplateService.saveOrUpdate(ygFileTemplate);
		String redisKey = String.format(RedisConstant.MALL_TEMPLATE_KEY, FileType.YiJiaDian.name());
		redisDao.set(redisKey, img, 0);
		return SUCCESS_MESSAGE;

	}

	@RequestMapping("getYiJiadianwMall")
	@ResponseBody
	public YgFileTemplate getYiJiadianwMall() {

		return ygFileTemplateService.find(FileType.YiJiaDian).get(0);
	}

	@RequestMapping("saveYjStart")
	@ResponseBody
	public Message saveYjStart(String img) {
		redisDao.set("YjStartPage", img, 0);

		return SUCCESS_MESSAGE;

	}

	@RequestMapping("getYjStart")
	@ResponseBody
	public String getYjStart() {
		return redisDao.get("YjStartPage");
	}

	/**
	 * 页面列表（生效时间）
	 *
	 * @param queryInfo 分页
	 * @return
	 * @date 2019年2月19日 14:46
	 */
	@RequestMapping("searchMallStartList")
	@ResponseBody
	public Map<String, Object> searchMallStartList(QueryInfo queryInfo,String imgType) {
		ResultSet<YgFileTemplate> resultSet = ygFileTemplateService.searchMallStartList(queryInfo,imgType);
		return resultSet.toDatatables(null);
	}

	/**
	 * 启用/禁用页面
	 *
	 * @param id        页面id
	 * @param startTime 生效时间
	 * @param status    数据状态
	 * @return
	 * @date 2019年2月19日 14:46
	 */
	@RequestMapping("updateStartTimeAndStatus")
	@ResponseBody
	public Message updateStartTimeAndStatus(@RequestParam Long id, Date startTime, @RequestParam DataStatus status) {
		return ygFileTemplateService.updateStartTimeAndStatus(id, startTime, status, getSession().getTrueName());
	}

	/**
	 * 获取页面模板
	 *
	 * @param id 页面id
	 * @return
	 * @date 2019年2月19日 14:46
	 */
	@RequestMapping("findMallTemplateById")
	@ResponseBody
	public Message findMallTemplateById(@RequestParam Long id) {
		YgFileTemplate fileTemplate = ygFileTemplateService.findById(id);
		
		return Message.success(fileTemplate);
	}

}
